import { successResponse, errorResponse } from "../../helpers.ts";

async function index(req, res, module) {
  try {
    const list = await module.query().paginate(req.query.page, req.query.perPage);
    return successResponse(res, {data: { items: list.items() }});
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

async function store(req, res, module) {
  try {
    const params = req.body;
    if (Object.keys(params).length === 0) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    const result = await module.query().insert(params);
    return successResponse(res, {msg: result ? "添加成功！" : "添加失败！"});
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg:"服务器错误！"});
  }
}

async function edit(req, res, module) {
  const { id } = req.params;
  if (!id) {
    return errorResponse(res, {msg: "无效的请求参数！"});
  }
  try {
    const result = await module.query().where({ id }).first();
    if (result) {
      return successResponse(res, {data: result});
    }
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

async function update(req, res, module) {
  try {
    const { id } = req.params;
    const params = req.body;
    if (!id || !params || Object.keys(params).length === 0)
      return errorResponse(res, {msg: "无效的请求参数！"});

    delete params.created_at;
    delete params.updated_at;
    const result = await module.query().where({ id }).update(params);
    return successResponse(res, {msg: result ? "保存成功！" : "保存失败！"});
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

async function destroy(req, res, module) {
  try {
    let { id } = req.params;
    if (!id) return errorResponse(res, {msg: "无效的请求参数！"});
    const ids = id
      .split(",")
      .map((item) => parseInt(item))
      .filter(Boolean);
    if (ids.length === 0) return errorResponse(res, {msg: "无效的ID列表！"});
    const result = module.query().whereIn("id", ids).delete();
    return successResponse(res, {msg: result ? "删除成功！" : "删除失败！"});
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

async function quickEditItem(req, res, module, id, otherParams) {
  try {
    if (!id || !otherParams || Object.keys(otherParams).length === 0) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    delete otherParams.created_at;
    delete otherParams.updated_at;
    const result = await module.query().where({ id }).update(otherParams);
    return successResponse(res, {msg: result ? "保存成功！" : "保存失败！"});
  } catch (error) {
    console.error("数据库错误：", error);
    return errorResponse(res, {msg: "服务器错误！"});
  }
}

// 一次性导出
export default {
  index,
  store,
  edit,
  update,
  destroy,
  quickEditItem,
};
